﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OpenSoftStore.BusinessLogic.Provider;
using OpenSoftStore.Client.Common;
using OpenSoftStore.Orm.Model;
using OpenSoftStore.BusinessLogic.Common;

namespace OpenSoftStore.Client.UIL.ManageProvider
{
    public partial class ProviderList : UserControl
    {
        #region
        private static ProviderList instance;
        private TreeLogic lgcTree;
        private ComboLogic comboBll;
        private ProviderLogic providerLogic;
        private List<T_ProviderPay> providerPayList;
        #endregion

        /// <summary>
        /// 返回一个该控件的实例。如果之前该控件已经被创建，直接返回已创建的控件。
        /// 此处采用单键模式对控件实例进行缓存，避免因界面切换重复创建和销毁对象。
        /// </summary>
        public static ProviderList Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new ProviderList();
                }
                //BindDataGrid(); // 每次返回该控件的实例前，都将对DataGridView控件的数据源进行重新绑定。
                return instance;
            }
        }

        /// <summary>
        /// 私有的控件实例化方法，创建实例只能通过该控件的Instance属性实现。
        /// </summary>
        private ProviderList()
        {
            InitializeComponent();
            Dock = DockStyle.Fill;
            lgcTree = new TreeLogic();
            comboBll = new ComboLogic();
            providerLogic = new ProviderLogic();
            BindDropDownList();
            SetUi();
            GetProvider();
            GetProviderPay();
            GetProviderPayInfo();
            SPACommon.SetDataGridStyle(DgvGrid);
            SPACommon.SetDataGridStyle(dgvPayInfo);
            SPACommon.SetDataGridStyle(dgvPayList);
            SPACommon.SetDataGridStyle(dgvPayItems);

            btnTree_Add.Visible= SysPowerManager.IsHavePower(SysPowerManager.管理供应商信息分类);
            btnTree_Update.Visible= SysPowerManager.IsHavePower(SysPowerManager.管理供应商信息分类);
            btnTree_Delete.Visible = SysPowerManager.IsHavePower(SysPowerManager.管理供应商信息分类);
            tlProviderAdd.Visible = SysPowerManager.IsHavePower(SysPowerManager.添加供应商);
            tlProviderUpdate.Visible = SysPowerManager.IsHavePower(SysPowerManager.修改供应商信息);
            tlProviderDelete.Visible = SysPowerManager.IsHavePower(SysPowerManager.删除供应商);
        }

        private void BindDropDownList()
        {
            ShopLogic.BindShop(cmbProvider);
            ShopLogic.BindShop(cmbShop);
            cmbBalance.DisplayMember = "Value";
            cmbBalance.ValueMember = "Key";
            cmbBalance.DataSource = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string,string>("YuFu","付款结余"),
                    new KeyValuePair<string,string>("YuShou","收款结余")
                };

            cmbOperator.ValueMember = "Value1";
            cmbOperator.DisplayMember = "DisplayText";
            cmbOperator.DataSource = comboBll.GetComboByBuzType("Operator");
        }

        private void SetUi()
        {
            trTree.Refresh();
            trProviderType.Refresh();
            tvPayTree.Refresh();

            lgcTree.SetTreeNode(lgcTree.GetProviderTree(), trTree);
            lgcTree.SetTreeNode(lgcTree.GetProviderTree(), trProviderType);
            lgcTree.SetTreeNode(lgcTree.GetProviderPayTree(), tvPayTree);

            tvPayTree.ExpandAll();
            trTree.ExpandAll();
            trProviderType.ExpandAll();

            trTree.SelectedNode = trTree.Nodes[0];
            SPACommon.SetTreeStyle(trTree);
            trProviderType.SelectedNode = trProviderType.Nodes[0];
            SPACommon.SetTreeStyle(trProviderType);
            tvPayTree.SelectedNode = tvPayTree.Nodes[0];
            SPACommon.SetTreeStyle(tvPayTree);
        }

        private void GetProviderPay()
        {
            dgvPayList.AutoGenerateColumns = false;
            string buzType = tvPayTree.SelectedNode.Text;
            string name = txtProviderName.Text.Trim();
            var from = dtpFrom.Value.Date;
            var to = dtpTo.Value.Date.AddDays(1).AddSeconds(-1);
            string whereStr = string.Format(" where  P.Name like '{0}%' and PP.AddTime between #{1}# and #{2}# ", name, from, to);
            if (tvPayTree.SelectedNode.Level != 0)
            {
                whereStr += " and PP.BuzType='" + buzType + "'";
            }
            dgvPayList.DataSource = providerLogic.GetProviderPay(whereStr, " order by PP.AddTime desc ");
            lblOrderCount.Text = dgvPayList.RowCount.ToString();
        }

        private void GetProvider()
        {
            string code = "";
            DgvGrid.AutoGenerateColumns = false;
            string name = txtSearch.Text.Trim();
            if (trTree.SelectedNode != null)
            {
                code = trTree.SelectedNode.Tag.ToString();
            }
            string whereStr = string.Format(" where T.Code like '{0}%' and P.Name like '{1}%' ", code, name);
            DgvGrid.DataSource = providerLogic.GetProviderList(whereStr);
            lblProviderCount.Text = DgvGrid.RowCount.ToString();
        }

        private void GetProviderPayInfo()
        {
            string name = txtProvider.Text.Trim();
            string condition = " where  Name like '" + name + "%'";
            if (cbProvider.Checked)
            {
                string balanceStr = cmbBalance.SelectedValue.ToString();
                string operatorStr = cmbOperator.SelectedValue.ToString();
                condition += string.Format("  and {0}{1}{2}", balanceStr, operatorStr, numValue.Value);
            }
            var from = dtpStart.Value.Date;
            var to = dtpEnd.Value.Date.AddDays(1).AddSeconds(-1);

            dgvPayInfo.AutoGenerateColumns = false;
            string whereStr = string.Format(" where AddTime between #{0}# and #{1}# ", from, to);
            dgvPayInfo.DataSource = providerLogic.GetProviderPayInfo(whereStr, condition);
            lblPayCount.Text = dgvPayInfo.RowCount.ToString();
        }


        private void toolStripLabel1_Click(object sender, EventArgs e)
        {
            var providerAddWindow = new ProviderAddWindow();
            providerAddWindow.SetTreeValue(trTree.SelectedNode.Name, trTree.SelectedNode.Text);
            providerAddWindow.ShowDialog();
        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            var provider = new ProviderLogic();
            string filer = textBox3.Text;
            if (DgvGrid != null) DgvGrid.DataSource = provider.SqlWhere<T_Provider>("Name like '" + filer + "%'");
        }

        private void toolStripLabel2_Click(object sender, EventArgs e)
        {
            ProviderAddWindow providerAddWindow = new ProviderAddWindow();
            if (DgvGrid.CurrentRow != null)
            {
                providerAddWindow.GetProvider(DgvGrid.CurrentRow.Cells["Id"].Value.ToString());
                providerAddWindow.ShowDialog();
            }
        }

        private void toolStripLabel3_Click_1(object sender, EventArgs e)
        {

            if (MessageBox.Show("确定要删除吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) != DialogResult.OK) return;
            if (DgvGrid.CurrentRow == null) return;
            var providerAddWindow = new ProviderAddWindow();
            var id = DgvGrid.CurrentRow.Cells["Id"].Value.ToString();

            if (id == "46872df4-47b1-4875-bdbb-1f8f8d1023ee")
            {
                FormSysMessage.ShowMessage("此数据为系统基础数据，不能删除！");
                return;
            }

            var provider = new ProviderLogic();
            provider.Delete(new T_Provider { Id = id });
            button7_Click(null, null);
        }


        public void button7_Click(object sender, EventArgs e)
        {
            GetProvider();
        }

        private void toolStripLabel6_Click(object sender, EventArgs e)
        {

            if (MessageBox.Show("确定要撤销单据吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) != DialogResult.OK) return;
            if (dgvPayList.CurrentRow == null) return;
            var id = dgvPayList.CurrentRow.Cells["Column28"].Value.ToString();
            var provider = new ProviderLogic();
            provider.DeletePay(id);

        }

        private void button5_Click(object sender, EventArgs e)
        {
            GetProviderPay();
        }

        private void btnTree_Add_Click(object sender, EventArgs e)
        {
            if (trTree.SelectedNode == null) return;
            trTree.LabelEdit = true;
            var treeNode = new TreeNode { Text = "新子项" };
            TreeNode tnParent = trTree.SelectedNode;
            tnParent.Nodes.Add(treeNode);
            trTree.SelectedNode = treeNode;
            treeNode.BeginEdit();
            DgvGrid.DataSource = null;
        }

        private void btnTree_Update_Click(object sender, EventArgs e)
        {
            if (trTree.SelectedNode == null) return;
            trTree.LabelEdit = true;
            trTree.SelectedNode.BeginEdit();
        }

        private void btnTree_Delete_Click(object sender, EventArgs e)
        {
            if (trTree.SelectedNode == null) return;
            string code = trTree.SelectedNode.Tag.ToString();
            int count = providerLogic.GetProviderView(" where T.Code like '" + code + "%'").Count();
            if (count > 0)
            {
                FormSysMessage.ShowMessage("该节点下仍有数据，不能删除！");
                return;
            }
            else
            {
                lgcTree.Delete(trTree);
            }

        }

        private void toolStripLabel4_Click(object sender, EventArgs e)
        {
            if (dgvPayInfo.CurrentRow == null) return;
            var id = dgvPayInfo.CurrentRow.Cells["Column26"].Value.ToString();
            var payInWindow = new PayInWindow();
            payInWindow.GetProviderId(id);
            payInWindow.Show();
        }

        private void toolStripLabel5_Click(object sender, EventArgs e)
        {
            if (dgvPayInfo.CurrentRow == null) return;
            var id = dgvPayInfo.CurrentRow.Cells["Column26"].Value.ToString();
            var payOutWindow = new PayOutWindow();
            payOutWindow.GetProviderId(id);
            payOutWindow.Show();
        }

        private void dgvPayList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //if (dgvPayList.CurrentRow == null) return;
            //var id = dgvPayList.CurrentRow.Cells["Column28"].Value.ToString();
            //dgvPayItems.DataSource = providerLogic.GetPayInItem(" where T_ProviderPayItem.PayId='" + id + "'");
            //lblOrderItemCount.Text = dgvPayItems.RowCount.ToString();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            GetProviderPayInfo();
        }

        private void tvPayTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            button5_Click(null, null);
            lblOrderCount.Text = DgvGrid.RowCount.ToString();
        }

        private void trTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (trTree.SelectedNode.Tag == null) return;
            button7_Click(null, null);
        }

        private void trProviderType_AfterSelect(object sender, TreeViewEventArgs e)
        {
            //dgvPayInfo.DataSource = null;
            //if (trProviderType.SelectedNode.Tag == null) return;
            //dgvPayInfo.DataSource = providerLogic.GetProviderPayInfo(" and T_Tree.Code like '" + trProviderType.SelectedNode.Tag.ToString() + "%'");
            lblPayCount.Text = dgvPayInfo.RowCount.ToString();
        }

        public void button4_Click_1(object sender, EventArgs e)
        {
            GetProviderPayInfo();
        }

        private void trTree_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            if (trTree.SelectedNode == null) return;
            trTree.SelectedNode.EndEdit(true);
            if (!lgcTree.SaveTreeNode(trTree, sender, e, "ProviderTree"))
                FormSysMessage.ShowSuccessMsg("保存失败！");
        }

        private void trProviderType_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {

        }

        private void BtnSearch_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                button7_Click(null, null);
            }
        }

        private void glassButton4_KeyUp(object sender, KeyEventArgs e)
        {
            if (Keys.Enter == e.KeyCode)
            {
                button4_Click_1(null, null);
            }
        }

        private void glassButton5_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                button5_Click(null, null);
            }
        }

        private void DgvGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1) return;
            var providerAddWindow = new ProviderAddWindow();
            var id = DgvGrid.CurrentRow.Cells["Id"].Value.ToString();
            providerAddWindow.GetProvider(id);
            providerAddWindow.ShowDialog();
        }

        private void cbProvider_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void dgvPayList_SelectionChanged(object sender, EventArgs e)
        {
            dgvPayItems.DataSource = null;
            if (dgvPayList.SelectedRows.Count > 0)
            {
                var id = dgvPayList.SelectedRows[0].Cells["Column28"].Value.ToString();
                dgvPayItems.DataSource = providerLogic.GetPayInItem(" where T_ProviderPayItem.PayId='" + id + "'");
                lblOrderItemCount.Text = dgvPayItems.RowCount.ToString();
            }
        }
    }
}
